package guidePage;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.xuegengwang.xuegengwang.MainActivity;
import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.service.UpdateService;
import com.foamtrace.photopicker.ImageConfig;
import com.igexin.sdk.PushManager;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import common.BaseActivity;
import common.Constant;
import common.Variable;
import https.InterNetController;
import push.service.MyIntentService;
import push.service.MyPushService;
import utils.FileUtils;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.VariousUtils;

/**
 * Created by admin on 2017/2/15.
 * 启动页
 */
@ContentView(R.layout.activity_loading_page)
public class LoadingPage extends BaseActivity {
    private final int PERMISSION = 321;

    private static DisplayImageOptions options;
    private static ImageLoaderConfiguration configuration;

    private MyHandler1 myHandler1;

    private class MyHandler1 extends Handler {
        WeakReference<LoadingPage> weakReference;

        public MyHandler1(LoadingPage activity) {
            this.weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            LoadingPage loadingPage = weakReference.get();
            Intent i = new Intent();
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    try {
                        JSONObject jsonObject = new JSONObject((String) msg.obj);
                        String last_ver = jsonObject.getString("last_ver");
                        //版本更新用的
                        if (!TextUtils.isEmpty(last_ver)) {
                            SPUtils.putString(Constant.LAST_VERSION, last_ver);
                            if (!VariousUtils.getVersion().equals(last_ver)) {
                                Variable.IS_NEW_VERSION = true;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    try{
                        JSONObject jsonObject = new JSONObject((String) msg.obj);
                        String token = jsonObject.getString("token");
                        if (!TextUtils.isEmpty(token)) {
                            //接口版本控制用的
                            SPUtils.putString(Constant.TOKEN, token);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case 0://第一次打开app
                    deleteOldData();
                    initAPP();
                    i.setClass(LoadingPage.this, GuidePage.class);
                    loadingPage.startActivity(i);
                    loadingPage.overridePendingTransition(0, 0);
                    LoadingPage.this.finish();
                    break;
                case 1:
                    initAPP();
                    i.setClass(LoadingPage.this, MainActivity.class);
                    loadingPage.startActivity(i);
                    loadingPage.overridePendingTransition(0, 0);
                    LoadingPage.this.finish();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myHandler1 = new MyHandler1(this);
        upLoadPhoneMessage();
        getPermission();
    }

    private void hasLoaded() {
        Message message = new Message();
        SharedPreferences sharedPreferences = SPUtils.getSharedPreferences();
        if (sharedPreferences.getBoolean(Constant.IS_FIRST_LOADED, true)) {
            //如果是第一次打开app
            message.what = 0;
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_FIRST_LOADED, false);
            edit.commit();
        } else {
            message.what = 1;
        }
        myHandler1.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler1.removeCallbacksAndMessages(null);
    }


    private void getPermission() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            MyLogUtils.e("wangic", "读取设备存储权限" + i);
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, permissions, PERMISSION);
            } else {
                startApp();
            }
        } else {
            startApp();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults.length > 0) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                        if (!b) {
                            Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                            startApp();
                        } else {
                            LoadingPage.this.finish();
                        }
                    } else {
                        startApp();
                    }
                } else {
                    LoadingPage.this.finish();
                }
            }
        }
    }


    private void startApp() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                hasLoaded();
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 500);
    }

    private void initAPP() {
        //初始化数据库
//        DBUtils.initDb();
        //删除数据库
        FileUtils.getInstance().deleteDir(new File(Constant.DB_DIR));
        //初始化个推
        PushManager.getInstance().initialize(this.getApplicationContext(), MyPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), MyIntentService.class);
        //imageLoaderINIT
        File cacheDir = StorageUtils.getOwnCacheDirectory(this, "xuegengwang/Cache");
        options = new DisplayImageOptions
                .Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .showImageForEmptyUri(R.mipmap.default_ima)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        configuration = new ImageLoaderConfiguration
                .Builder(this)
                .diskCacheFileCount(500)//设置最大下载图片数
                .memoryCacheSize(30 * 1024 * 1024)
                .diskCacheSize(500 * 1024 * 1024)
                .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
                .defaultDisplayImageOptions(options)
                .build();
        //初始化图片选择器
        ImageLoader.getInstance().init(configuration);
        initPictureSelector();
    }

    private void initPictureSelector() {
        ImageConfig config = new ImageConfig();
        config.minHeight = 400;
        config.minWidth = 400;
        config.mimeType = new String[]{"image/jpeg", "image/png"}; // 图片类型 image/gif ...
        config.minSize = 1 * 1024 * 1024; // 1Mb 图片大小
    }

    private void deleteOldData() {
        //第一次打开app时需要清掉原来的数据
        FileUtils.getInstance().deleteDir(new File(Constant.CACHE_DIR));
        FileUtils.getInstance().deleteDir(new File(Constant.VOLUNTEERS_DIR));
    }

    //上传手机信息
    public void upLoadPhoneMessage() {
        String phoneType = android.os.Build.MODEL; // 手机型号
        String androidType = Build.VERSION.RELEASE; // 当前安卓系统版本
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("ver", VariousUtils.getVersion());
        hashMap.put("os", "android");
        hashMap.put("deviceinfo", phoneType + ":" + androidType);
        hashMap.put("devicetoken", "");
        hashMap.put("clientid", SPUtils.getSharedPreferences().getString(Constant.CLIENTID, ""));

        new InterNetController(this, Constant.DEVICEINFO, myHandler1, hashMap, 0, false);
    }
}
